package com.fish.yssb.ui.page.activity.realTime;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fish.yssb.Consts;
import com.fish.yssb.R;
import com.fish.yssb.api.retData;
import com.fish.yssb.api.setApi;
import com.fish.yssb.db.RealmDb;
import com.fish.yssb.db.bean.BaseInfoTable;
import com.fish.yssb.ui.page.activity.base.BaseActivity;
import com.fish.yssb.ui.page.adapter.realtimeYCListAdapter;
import com.fish.yssb.ui.page.util.TopToastUtil;
import com.hy.srv101.I4YData;
import com.hy.srv101.Up4YData;
import com.jaeger.library.StatusBarUtil;
import com.syd.oden.circleprogressdialog.core.CircleProgressDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


/**
 * A login screen that offers login via email/password.
 */
public class RealTimeListYCActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = RealTimeListYCActivity.class.getSimpleName();

    LinearLayout tv_back;
    TextView tv_toptitle;

    ImageView tv_set;
    private RecyclerView recyclerView;
    private realtimeYCListAdapter adapter;

    private ArrayList<BaseInfoTable> arrayList;

    private CircleProgressDialog circleProgressDialog;
    private RelativeLayout ll_para_1, ll_para_2, ll_para_3;

    private Boolean isshow  =true;
    final Handler mHandler = new Handler();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            Collection<I4YData> list = setApi.getInstance(RealTimeListYCActivity.this).getRealData(3);
            HashMap map = new HashMap();
            Iterator it = list.iterator();
            while(it.hasNext()){
                Up4YData cell = (Up4YData)it.next();
                short chanID = cell.wChannel;
                String val = "0";
                switch (cell.type)
                {
                    //byte
                    case 1:
                        try {
                            val = String.valueOf(cell.cVal);
                        }catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                        break;
                    //short
                    case 2:
                        val = String.valueOf(cell.sVal16);
                        break;
                    //int
                    case 3:
                        val = String.valueOf(cell.sVal32);
                        break;
                    //float
                    case 4:
                        DecimalFormat decimalFormat=new DecimalFormat(".000");
                        val=decimalFormat.format(cell.fVal32);
                        break;

                }

                String str = "0x"+ byteToHex(chanID);
                map.put(str,val);

                for(int i=0;i<arrayList.size();i++)
                {

                    String  strVal =  (String) map.get( arrayList.get(i).getConnAdr());
                    arrayList.get(i).setDefualtVal(strVal);

                }
                adapter.replaceAll(arrayList);
                adapter.notifyDataSetChanged();
            }
            mHandler.postDelayed(this, 500);
        }
    };


    @Subscribe
    public void onEvent(final retData result) {
        //接收以及处理数据
        runOnUiThread(new Runnable() {
            public void run() {
                int strType = result.getType();
                int ret = result.getRet();
                int status = result.getStatus();

                if(strType == Consts.cm_r_real_para)
                {
                    circleProgressDialog.dismiss();
                    if(ret == Consts.cm_timeout) {
                        TopToastUtil.getInstance(RealTimeListYCActivity.this, R.layout.showdialog).showShortToast("命令执行超时");
                    }

                    if(ret == Consts.cm_end) {
                        if(status == 1) {

//                            TopToastUtil.getInstance(RealTimeListYCActivity.this, R.layout.showdialog).showShortToast("命令执行成功");
                        }else{
                            TopToastUtil.getInstance(RealTimeListYCActivity.this, R.layout.showdialog).showShortToast("命令执行失败");
                        }
                    }
                }
            }
        });
    };

    private final static String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

//    public String byteToHex(int n) {
//
//        if(n>65535)
//        {
//            n = n-65535;
//        }
//        int m = n/256;
//        int m1= n%256;
//
//
//        int d1 = m/16;
//        int d2 = m%16;
//        int d3 = m1 / 16;
//        int d4 = m1 % 16;
//        return hexArray[d3] + hexArray[d4]+hexArray[d1] + hexArray[d2];
//    }

    public String byteToHex(int n) {

        if(n>65535)
        {
            n = n-65535;
        }
        int m = n/256;
        int m1= n%256;


        int d1 = m/16;
        int d2 = m%16;
        int d3 = m1 / 16;
        int d4 = m1 % 16;
        return hexArray[d1] + hexArray[d2]+hexArray[d3] + hexArray[d4];
    }


    public static void start(Context context) {
        Intent intent = new Intent(context, RealTimeListYCActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setDarkMode(this);
        setContentView(R.layout.activity_realtime_yc_list);
        initview();
        EventBus.getDefault().register( this );
        circleProgressDialog = new CircleProgressDialog(RealTimeListYCActivity.this);
        circleProgressDialog.setText("命令执行中");


//        tv_set.animate().rotation(90);

//        circleProgressDialog.showDialog();
        int ret =  setApi.getInstance(this).r_real_para();
        //主线程中调用：
        mHandler.postDelayed(r, 500);//延时100毫秒
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
        if (rotate != null) {
            tv_set.startAnimation(rotate);
        }  else {
            tv_set.setAnimation(rotate);
            tv_set.startAnimation(rotate);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_set.clearAnimation();
            }
        }, 3000);
    }




    //初始化视图
    @SuppressLint("WrongViewCast")
    private void initview() {
        //登录层、下拉层、其它登录方式层
        recyclerView = (RecyclerView) findViewById(R.id.recylerview);
        recyclerView.setHasFixedSize(true);

        tv_toptitle = findViewById(R.id.tv_toptitle);
        tv_toptitle.setText("遥测");

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapter = new realtimeYCListAdapter());

        adapter.replaceAll(getData());

        tv_back = findViewById(R.id.tv_back);
        tv_set = findViewById(R.id.tv_set);
        tv_set.setOnClickListener(this);
        tv_back.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_set:
                Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate_anim);
                if (rotate != null) {
                    tv_set.startAnimation(rotate);
                }  else {
                    tv_set.setAnimation(rotate);
                    tv_set.startAnimation(rotate);
                }

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tv_set.clearAnimation();
                    }
                }, 3000);
                int ret =  setApi.getInstance(this).r_real_para();
                break;
            default:
                break;
        }


    }

    public ArrayList<BaseInfoTable> getData()
    {
        arrayList = (ArrayList) RealmDb
                .getInstance()
                .queryRealmObjectsByData(BaseInfoTable.class,"paraType",2);

        return arrayList;
    }

}

